# -*- coding: utf-8 -*-

from flask import render_template, url_for, flash, redirect, request
from flask_login import current_user, login_user, logout_user, login_required
from flask import current_app

from .forms import LoginForm, RegisterForm
from . import auth
from ..models import User, Role, UserStatus
from .. import db
from ..decorators import admin_required


@auth.route('/login', methods=['post', 'get'])
def login():

    if current_user.is_authenticated:
        return redirect(url_for('main.index'))

    form = LoginForm()

    if form.validate_on_submit():
        user = User.query.filter(User.username == form.username.data).first()
        if user is not None and user.verify_password(form.password.data) and \
                user.is_admin:
            if login_user(user, form.remember_me.data):
                return redirect(request.args.get('next') or url_for('main.index'))
        flash(u'密码错误或用户不存在。')

    return render_template('auth/login.html', form=form)


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))


@auth.route('/create_user', methods=['post', 'get'])
@admin_required
def create_user():
    form = RegisterForm()

    form.role.choices = [(r.id, r.name) for r in Role.query.order_by('id')]
    form.status.choices = UserStatus.getAll()

    if form.validate_on_submit():
        user = User(username=form.username.data,
                    nickname=form.nickname.data,
                    password=form.password.data,
                    status=form.status.data,
                    role_id=form.role.data)
        db.session.add(user)
        db.session.commit()
        flash(u'新用户添加成功！')
        return redirect(url_for('main.user_list'))

    return render_template('auth/register.html', form=form)